<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Models\Order;
use App\Models\Station;

class KepaiController extends Controller
{
    // 6.1 对账
    public function purchase(Request $request) {
        $client = new Client();
        
        $url = env('WECHAT_KEPAI_URL').'/purchase';
        $json = [
            "date" => '20201101',
            "merchantno" => env('WECHAT_KEPAI_MERCHANT_NO'),
            "timestamp" => time(),
        ];

        $json = $this->sign($json);

        $response = $client->request('GET', $url, [
            'query' => $json,
        ]);

        $data = json_decode($response->getBody()->getContents());

        return $this->success($data);
    }

    // 6.2 订单查询
    public function queryOrder(Request $request) {
        $url = env('WECHAT_KEPAI_URL').'/order';
        $json = [
            "merchantno" => env('WECHAT_KEPAI_MERCHANT_NO'),
            // "orderid" => '20201031000001',
            "timestamp" => 1604454668,
        ];

        $json = $this->sign($json);

        return $this->success($json);
    }

    // 6.3 客户余额查询
    public function accountbalance(Request $request) {
        $client = new Client();
        $url = env('WECHAT_KEPAI_URL').'/accountbalance';
        $json = [
            "merchantNo" => env('WECHAT_KEPAI_MERCHANT_NO'),
            "timestamp" => time(),
        ];
        $json = $this->sign($json);
        return [$json];

        $response = $client->request('GET', $url, [
            'query' => $json,
        ]);

        $data = json_decode($response->getBody()->getContents());
        
        return $this->success($data);
    }

    // 生成加密参数
    public function sign($json) {
        $string = '';
        foreach($json as $key => $value) {
            $string .=  $key.$value;
        }
        $sign = $string . env('WECHAT_KEPAI_SIGN');
        $json['sign'] = hash("sha256", $sign);
        return $json;
    }

    public function returnSign($json) {
        $string = '';
        foreach($json as $key => $value) {
            $string .=  $key.$value;
        }
        $sign = $string . env('WECHAT_KEPAI_SIGN');
        return hash("sha256", $sign);
    }

    // 7.1 订单回调接口
    public function OrderCallback(Request $request) {
        $result = json_decode(Request::createFromGlobals()->getContent());

        if ($result->merchantno != env('WECHAT_KEPAI_MERCHANT_NO')) {
            return $this->commonResult('40999', '商户号错误', 2);
        }

        $time = time();
        if ($result->timestamp < $time - 600 || $result->timestamp > $time + 600) {
            return $this->commonResult('40999', '时间不正确', 2);
        }

        $productList = $result->productList;
        $productString = '';
        foreach ($productList as $item) {
            foreach($item as $key => $value) {
                if ($value != '000') {
                    return $this->commonResult('40999', '仅限柴油油品使用', 2);
                }
                $productString .= $key.$value;
            }
        }

        // 加密校验
        $json = [
            'merchantno' => $result->merchantno,
            'noncestr' => $result->noncestr,
            'orderid' => $result->orderid,
            '' => $productString,
            'siteid' => $result->siteid,
            'timestamp' => $result->timestamp,
        ];
        if ($result->sign != $this->returnSign($json)) {
            return $this->commonResult('50000', '签名错误', 2);
        }

        $order = Order::where([
            'order_id' => $result->orderid
        ])->first();
        if (!$order) {
            return $this->commonResult('40501', '订单不存在！', 2);
        }
        if ($order->station_id != $result->siteid) {
            return $this->commonResult('40999', '请在订单指定油站使用！', 2);
        }
        if ($order->order_status == 7) {
            return $this->commonResult('40501', '订单状态异常，不允许核销', 2);
        }
        if ($order->order_status == 8) {
            return $this->commonResult('40501', '订单已过期', 2);
        }
        if ($order->order_status == 3) {
            return $this->commonResult('40501', '订单已核销', 2);
        }
        if ($order->order_status == 2) {
            return $this->OrderResult('00000', '成功', 1, $order->order_amount / 100, $order->amount / 100, $order->phone);
        }
        return $this->commonResult('50000', '系统错误', 2);
    }

    // 返回码
    public function OrderResult($code, $respMsg, $status, $amount = null, $realpay = null, $phone = null) {
        return [
            'respCode' => $code,
            'respMsg' => $respMsg,
            'amount' => $amount,
            'paidAccount' => $realpay,
            'phoneNumber' => $phone,
            'status' => $status
        ];
    }

    public function convertUrlQuery($query) {
        $queryParts = explode('&', $query);
        
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        
        return $params;
    }

    // 7.2 订单核销通知回调
    public function VerificationCallback(Request $request) {
        $result = $this->convertUrlQuery(Request::createFromGlobals()->getContent());

        if ($result['merchantno'] != env('WECHAT_KEPAI_MERCHANT_NO')) {
            return $this->commonResult('40999', '商户号错误', 2);
        }

        $time = time();
        if ($result['timestamp'] < $time - 600 || $result['timestamp'] > $time + 600) {
            return $this->commonResult('40999', '时间不正确', 2);
        }

        // 加密校验
        $json = [
            'fillingtime' => $result['fillingtime'],
            'merchantno' => $result['merchantno'],
            'noncestr' => $result['noncestr'],
            'orderid' => $result['orderid'],
            'siteid' => $result['siteid'],
            'status' => $result['status'],
            'timestamp' => $result['timestamp'],
        ];
        if ($result['sign'] != $this->returnSign($json)) {
            return $this->commonResult('50000', '签名错误', 2);
        }

        if ($result['status'] == '1') {
            $order = Order::where([
                'order_id' => $result['orderid'],
                'station_id' => $result['siteid'],
                'order_status' => 2
            ])->first();
            if (!$order) return $this->commonResult('40501', '订单不存在', 2);
            $order->order_status = 3;
            $order->check_time = date("Y-m-d H:i:s");
            $order->save();

            // 微信消息模板，核销通知
            $WechatController = new WechatController();
            $station = Station::where('code_id', $order->station_id)->first();
            $WechatController->check($order, $station);
            return $this->commonResult();
        } else if ($result['status'] == '2'){
            return $this->commonResult('00000', '核销失败', 1);
        }
        return $this->commonResult('50000', '系统异常', 2);
    }

    // 返回码
    public function commonResult($code = '00000', $respMsg = '成功', $status = 1) {
        return [
            'respCode' => $code,
            'respMsg' => $respMsg,
            'status' => $status
        ];
    }

}
